package com.naiterui.ehp.bp.utils.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * spring容器持有者
 *
 * @author wangzehao
 */
@Component
public final class SpringContextHolder implements ApplicationContextAware {

    /**
     * spring容器
     */
    private static ApplicationContext context;

    public static <T> T getBean(String beanName, Class<T> clazz) {
        Assert.notNull(context, "ApplicationContext not be null");
        return context.getBean(beanName, clazz);
    }

    public static <T> T getBean(Class<T> clazz) {
        Assert.notNull(context, "ApplicationContext not be null");
        return context.getBean(clazz);
    }

    public static boolean containsBean(String beanName){
        Assert.notNull(context, "ApplicationContext not be null");
        return context.containsBean(beanName);
    }

    /**
     * 设置spring容器
     * <P>Author : zhouyanxin </P>
     * <P>Date : 2014-10-12 </P>
     *
     * @param context
     *
     * @throws BeansException
     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
     */
    @Override
    public void setApplicationContext(@NonNull ApplicationContext context) throws BeansException {
        SpringContextHolder.context = context;
    }

}
